<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { View } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'
import { useTokenStore } from '@/stores/token'
import { Download } from '@element-plus/icons-vue'; // 导入 Download 图标组件
const tokenStore = useTokenStore()

interface ScrapRequest {
  id: number
  serialNumber: string
  applicantId: number
  departmentName: string
  reason: string
  scrapType: string
  scrapFileUrl: string
  status: string
  submitTime: string
  updateTime: string
}

interface ScrapApproval {
  id: number
  requestId: number
  approverId: number
  approverDepartment: string
  approvalResult: string
  approvalOpinion: string
  approvalTime: string
}

interface ScrapDisposal {
  id: number
  scrapRequestId: number
  disposalMethod: string
  income: number
  disposalTime: string
  operatorId: number
  remarks: string
}

interface ScrapRequestListResponse {
  current: number
  total: number
  pages: number
  size: number
  records: ScrapRequest[]
}

interface ScrapApprovalListResponse {
  current: number
  total: number
  pages: number
  size: number
  records: ScrapApproval[]
}

interface ScrapDisposalListResponse {
  current: number
  total: number
  pages: number
  size: number
  records: ScrapDisposal[]
}

const statusTypeMap = {
  '待审批': '待审批',
  '已通过': '已通过',
  '已驳回': '已驳回'
} as const

const scrapTypeMap = {
  '使用年限到期': '使用年限到期',
  '损坏无法修复': '损坏无法修复',
  '维修成本过高': '维修成本过高'
} as const

const approvalResultMap = {
  '通过': '通过',
  '驳回': '驳回'
} as const

const disposalMethodMap = {
  '变卖': '变卖',
  '丢弃': '丢弃',
  '捐赠': '捐赠',
  '回收': '回收'
} as const

const getStatusTypeLabel = (value: string): string => {
  return statusTypeMap[value as keyof typeof statusTypeMap] || '未知状态'
}

const getScrapTypeLabel = (value: string): string => {
  return scrapTypeMap[value as keyof typeof scrapTypeMap] || '未知类型'
}

const getApprovalResultLabel = (value: string): string => {
  return approvalResultMap[value as keyof typeof approvalResultMap] || '未知结果'
}

const getDisposalMethodLabel = (value: string): string => {
  return disposalMethodMap[value as keyof typeof disposalMethodMap] || '未知方式'
}

const scrapApi = {
  getScrapRequests: (params: any) => {
    return request<ScrapRequestListResponse>({
      method: 'GET',
      url: '/scrap/list',
      params: params
    })
  },

  getApprovalHistory: (requestId: number) => {
    return request<ScrapApprovalListResponse>({
      method: 'GET',
      url: `/scrap/approval/list/${requestId}`
    })
  },

  getDisposalHistory: (requestId: number) => {
    return request<ScrapDisposalListResponse>({
      method: 'GET',
      url: `/scrap/disposal/history/${requestId}`
    })
  },

  getSerialSuggestions: (keyword: string) => request<string[]>({
    method: 'GET',
    url: '/device/serial/suggestions',
    params: { keyword }
  })
}

const scrapRequests = ref<ScrapRequest[]>([])
const approvalHistory = ref<ScrapApproval[]>([])
const disposalHistory = ref<ScrapDisposal[]>([])
const requestDisposalStatus = ref<Record<number, boolean>>({})
const serialNumberOptions = ref<string[]>([])
const loadingSerialNumbers = ref(false)

const searchParams = ref({
  serialNumber: null as string | null,
  status: null as string | null,
  scrapType: null as string | null
})

const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)

const showApprovalHistoryDialog = ref(false)
const showDisposalHistoryDialog = ref(false)
const currentRequestId = ref<number | null>(null)

onMounted(() => {
  getScrapRequests()
})

const fetchSerialSuggestions = async (query: string) => {
  if (query) {
    loadingSerialNumbers.value = true
    try {
      const res = await scrapApi.getSerialSuggestions(query)
      serialNumberOptions.value = res.data
    } catch {
      ElMessage.error('获取设备序列号失败')
    } finally {
      loadingSerialNumbers.value = false
    }
  } else {
    serialNumberOptions.value = []
  }
}

const getScrapRequests = async () => {
  try {
    const params: {
      page: number;
      size: number;
      serialNumber?: string;       // Assuming serialNumber is a string and optional
      status?: string;             // Assuming status is a string and optional
      type?: string;               // Assuming type is a string and optional
      applicantId: string | number; // Assuming applicantId is either a string or number, and required as it's from tokenStore
      [key: string]: any;          // Allows for any other dynamic properties
    } = {
      page: pageNum.value,
      size: pageSize.value,
      serialNumber: searchParams.value.serialNumber!,
      status: searchParams.value.status!,
      type: searchParams.value.scrapType!,
      applicantId: tokenStore.id,
    };

    Object.keys(params).forEach(key => {
      if (params[key] === null || params[key] === undefined || params[key] === '') {
        delete params[key]
      }
    })

    const response = await scrapApi.getScrapRequests(params)
    scrapRequests.value = response.data.records
    total.value = response.data.total
    
    // 获取每个申请的处理状态
    await checkDisposalStatusForRequests()
  } catch (error) {
    ElMessage.error('获取报废申请列表失败')
  }
}

const checkDisposalStatusForRequests = async () => {
  for (const request of scrapRequests.value) {
    try {
      // 只有状态为"已通过"的申请才检查处理状态
      if (request.status === '已通过') {
        const response = await scrapApi.getDisposalHistory(request.id)
        requestDisposalStatus.value[request.id] = (response as any).data.length > 0
      } else {
        requestDisposalStatus.value[request.id] = false
      }
    } catch (error) {
      requestDisposalStatus.value[request.id] = false
    }
  }
}

const getApprovalHistory = async (requestId: number) => {
  try {
    currentRequestId.value = requestId
    const response = await scrapApi.getApprovalHistory(requestId)
    approvalHistory.value = (response as any).data
    showApprovalHistoryDialog.value = true
  } catch (error) {
    ElMessage.error('获取审批历史失败')
  }
}

const getDisposalHistory = async (requestId: number) => {
  try {
    currentRequestId.value = requestId
    const response = await scrapApi.getDisposalHistory(requestId)
    disposalHistory.value = (response as any).data
    showDisposalHistoryDialog.value = true
  } catch (error) {
    ElMessage.error('获取处理历史失败')
  }
}

const search = () => {
  pageNum.value = 1
  getScrapRequests()
}

const resetSearch = () => {
  searchParams.value = {
    serialNumber: null,
    status: null,
    scrapType: null
  }
  pageNum.value = 1
  getScrapRequests()
}

const onSizeChange = (size: number) => {
  pageSize.value = size
  getScrapRequests()
}

const onCurrentChange = (num: number) => {
  pageNum.value = num
  getScrapRequests()
}

const downloadFile = (url: string) => {
  if (!url) {
    ElMessage.warning('没有可下载的附件')
    return
  }
  
  const link = document.createElement('a')
  link.href = url
  link.target = '_blank'
  link.download = url.split('/').pop() || 'attachment'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

const isImageFile = (url: string): boolean => {
  return /\.(jpg|jpeg|png|gif|bmp|webp)$/i.test(url)
}

</script>

<template>
  <!-- <div class="maintenance-wrapper"> -->
    <el-card class="card-box">
      <div class="header">
        <h2>报废处理情况跟踪</h2>
      </div>

      <el-form inline class="filter-bar">
        <el-form-item label="设备ID:">
          <el-select
            v-model="searchParams.serialNumber"
            filterable remote clearable reserve-keyword
            placeholder="请输入设备ID"
            :remote-method="fetchSerialSuggestions"
            :loading="loadingSerialNumbers"
            class="input-short"
          >
            <el-option
              v-for="item in serialNumberOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态:">
          <el-select
            v-model="searchParams.status"
            placeholder="请选择状态"
            clearable
            class="input-short"
          >
            <el-option
              v-for="item in Object.values(statusTypeMap)"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="报废类型:">
          <el-select
            v-model="searchParams.scrapType"
            placeholder="请选择报废类型"
            clearable
            class="input-short"
          >
            <el-option
              v-for="item in Object.values(scrapTypeMap)"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <div class="responsive-table-container">
        <table class="custom-table">
          <thead>
            <tr>
              <th>编号</th>
              <th>设备ID</th>
              <th>申请人ID</th>
              <th>部门ID</th>
              <th>报废类型</th>
              <th>报废原因</th>
              <th>附件</th>
              <th>状态</th>
              <th>处理情况</th>
              <th>提交时间</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="item in scrapRequests" :key="item.id">
              <td>{{ item.id }}</td>
              <td>{{ item.serialNumber }}</td>
              <td>{{ item.applicantId }}</td>
              <td>{{ item.departmentName }}</td>
              <td>{{ getScrapTypeLabel(item.scrapType) }}</td>
              <td class="truncate">{{ item.reason }}</td>
              <td>
  <template v-if="item.scrapFileUrl">
    <template v-if="isImageFile(item.scrapFileUrl)">
      <el-popover
        placement="left"
        trigger="hover"
        :width="325"
        popper-class="image-popover"
      >
        <template #reference>
          <img
            :src="item.scrapFileUrl"
            class="thumbnail-img"
            alt="缩略图"
            @click="downloadFile(item.scrapFileUrl)"
          />
        </template>
        <img :src="item.scrapFileUrl" class="preview-img" alt="大图预览" />
      </el-popover>
      <a
        :href="item.scrapFileUrl"
        :download="item.scrapFileUrl.split('/').pop()"
        class="thumbnail-download"
        title="点击下载"
      />
    </template>
    <el-button
      v-else
      :icon="Download"
      type="primary"
      link
      @click="downloadFile(item.scrapFileUrl)"
    >
      下载附件
    </el-button>
  </template>
  <span v-else class="no-attachment">无附件</span>
</td>
              <td>
                <el-tag :type="item.status === '已通过' ? 'success' : item.status === '已驳回' ? 'danger' : 'warning'">
                  {{ getStatusTypeLabel(item.status) }}
                </el-tag>
              </td>
              <td>
                <el-tag :type="item.status === '已通过' && requestDisposalStatus[item.id] ? 'success' : 'warning'">
                  {{ item.status === '已通过' ? (requestDisposalStatus[item.id] ? '已处理' : '未处理') : '不可处理' }}
                </el-tag>
              </td>
              <td>{{ item.submitTime }}</td>
              <td>
                <div class="action-btns">
                  <el-button
                    :icon="View"
                    circle
                    plain
                    size="small"
                    type="info"
                    @click="getApprovalHistory(item.id)"
                    :disabled="item.status === '待审批'"
                  />
                  <el-button
                    :icon="View"
                    circle
                    plain
                    size="small"
                    type="primary"
                    @click="getDisposalHistory(item.id)"
                    :disabled="item.status !== '已通过' || !requestDisposalStatus[item.id]"
                  />
                </div>
              </td>
            </tr>
            <tr v-if="scrapRequests.length === 0">
              <td colspan="10" class="text-center py-4">
                <el-empty description="暂无数据" />
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pageNum"
          v-model:page-size="pageSize"
          :page-sizes="[3, 5, 7, 10]"
          layout="total, sizes, prev, pager, next, jumper"
          background
          :total="total"
          @size-change="onSizeChange"
          @current-change="onCurrentChange"
        />
      </div>
    </el-card>

    <el-dialog 
      v-model="showApprovalHistoryDialog" 
      :title="`审批历史 - 申请ID: ${currentRequestId}`" 
      width="70%"
      top="5vh"
    >
      <el-table :data="approvalHistory" style="width: 100%" border>
        <el-table-column
          label="审批人ID"
          prop="approverId"
          width="100px"
        />
        <el-table-column
          label="审批部门"
          prop="approverDepartment"
          width="120px"
        />
        <el-table-column
          label="审批结果"
          prop="approvalResult"
          width="100px"
          :formatter="(row: ScrapApproval) => getApprovalResultLabel(row.approvalResult)"
        />
        <el-table-column
          label="审批意见"
          prop="approvalOpinion"
          width="200px"
        />
        <el-table-column
          label="审批时间"
          prop="approvalTime"
          width="166px"
        />
        <template #empty>
          <el-empty description="暂无审批历史记录" />
        </template>
      </el-table>
    </el-dialog>

    <el-dialog 
      v-model="showDisposalHistoryDialog" 
      :title="`处理历史 - 申请ID: ${currentRequestId}`" 
      width="70%"
      top="5vh"
    >
      <el-table :data="disposalHistory" style="width: 100%" border>
        <el-table-column
          label="处理ID"
          prop="id"
          width="80px"
        />
        <el-table-column
          label="处理方式"
          prop="disposalMethod"
          width="120px"
          :formatter="(row: ScrapDisposal) => getDisposalMethodLabel(row.disposalMethod)"
        />
        <el-table-column
          label="收入(元)"
          prop="income"
          width="120px"
        />
        <el-table-column
          label="操作人ID"
          prop="operatorId"
          width="100px"
        />
        <el-table-column
          label="处理时间"
          prop="disposalTime"
          width="166px"
        />
        <el-table-column
          label="备注"
          prop="remarks"
          width="200px"
        />
        <template #empty>
          <el-empty description="暂无处理历史记录" />
        </template>
      </el-table>
    </el-dialog>
  <!-- </div> -->
</template>

<style lang="scss" scoped>
.maintenance-wrapper {
  min-height: 100vh;
  padding: 1rem;
  box-sizing: border-box;
  background-color: #f0f2f5;
  display: flex;
  justify-content: center;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  color: #2c3e50;
}

.card-box {
  width: 100%;
  max-width: 100%;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  display: flex;
  flex-direction: column;
  padding: 0;
  overflow: hidden;
}

.header {
  padding: 0.8rem 1.2rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #e6eaf0;
  background-color: #f7f9fc;
  h2 {
    font-weight: 600;
    font-size: 1.4rem;
    color: #333;
    user-select: none;
    margin: 0;
  }
}

.filter-bar {
  padding: 0.8rem 1.2rem;
  background-color: #fafbfc;
  border-bottom: 1px solid #e6eaf0;
  display: flex;
  flex-wrap: nowrap;
  align-items: center;
  overflow-x: auto;
  white-space: nowrap;
  gap: 0.8rem;

  .el-form-item {
    margin-bottom: 0 !important;
    flex-shrink: 0;
    label {
      font-weight: 500;
      color: #606266;
      font-size: 0.9rem;
    }
    .input-short {
      width: 160px;
    }
  }

  .el-button {
    height: 32px;
    font-weight: 500;
    padding: 0 12px;
    flex-shrink: 0;
  }
}

.responsive-table-container {
  overflow-x: auto;
  background: #fff;
  padding: 0.8rem;
}

.custom-table {
  width: 100%;
  border-collapse: separate;
  border-spacing: 0 6px;
  font-size: 0.9rem;

  thead tr {
    background-color: #f5f7fa;
    color: #606266;
    font-weight: 600;
    user-select: none;
  }

  th, td {
    padding: 8px 12px;
    text-align: left;
    vertical-align: middle;
    white-space: nowrap;
  }

  th {
    font-size: 0.85rem;
  }

  tbody tr {
    background-color: #fff;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
    transition: background-color 0.2s ease;

    &:hover {
      background-color: #f4f9ff;
    }
  }

  .truncate {
    max-width: 180px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .action-btns {
    display: flex;
    gap: 0.4rem;

    .el-button {
      padding: 0;
      width: 28px;
      height: 28px;
      display: flex;
      justify-content: center;
      align-items: center;
      border-radius: 50%;
    }
  }
}

.pagination-container {
  background-color: #fafbfc;
  padding: 0.8rem;
  border-top: 1px solid #e6eaf0;
  display: flex;
  justify-content: center;
}

.text-center {
  text-align: center;
}

.py-4 {
  padding-top: 1rem;
  padding-bottom: 1rem;
}

@media (max-width: 1200px) {
  .filter-bar {
    gap: 0.6rem;
    
    .input-short {
      width: 140px;
    }
  }
  
  .custom-table {
    font-size: 0.85rem;
    
    th, td {
      padding: 6px 8px;
    }
  }
}

@media (max-width: 992px) {
  .header {
    padding: 0.6rem 1rem;
    
    h2 {
      font-size: 1.2rem;
    }
  }
  
  .filter-bar {
    padding: 0.6rem 1rem;
  }
  
  .responsive-table-container {
    padding: 0.6rem;
  }
}
.file-preview-wrapper {
  margin-top: 8px;
  display: flex;
  align-items: center;
  position: relative;
}

.file-preview {
  position: relative;
  display: inline-block;
  cursor: pointer;
  width: 80px;
  height: 80px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
  background-color: #f5f7fa;
  text-align: center;
  line-height: 80px;
  color: #606266;
  font-size: 12px;
  transition: border-color 0.3s ease;
}

.file-preview:hover {
  border-color: #409eff;
}

.preview-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.file-name {
  display: block;
  padding: 0 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.file-hover-preview {
  position: absolute;
  top: 0;
  z-index: 20;
  display: none;
  background: white;
  padding: 6px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  min-width: 120px;
  max-width: 200px;
  max-height: 200px;
  white-space: normal;
}

.left-preview {
  right: 100%; // 左侧显示
  margin-right: 10px;
}

.zoom-img {
  width: 100%;
  height: auto;
  max-height: 180px;
  object-fit: contain;
}

.zoom-text {
  color: #303133;
  font-size: 14px;
  word-break: break-all;
}

.file-preview:hover .file-hover-preview {
  display: block;
}
.attachment-thumbnail {
  display: inline-block;
  width: 40px;
  height: 40px;
  line-height: 40px;
  text-align: center;
  vertical-align: middle;
}

.thumbnail-img {
  max-width: 100%;
  max-height: 100%;
  border-radius: 4px;
  object-fit: cover;
  cursor: pointer;
  box-shadow: 0 0 3px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s ease;
}

.thumbnail-img:hover {
  transform: scale(1.1);
}

.attachment-thumbnail {
  display: inline-block;
  width: 40px;
  height: 40px;
  line-height: 40px;
  text-align: center;
  vertical-align: middle;
}

.thumbnail-img {
  max-width: 100%;
  max-height: 100%;
  border-radius: 4px;
  object-fit: cover;
  cursor: pointer;
  box-shadow: 0 0 3px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s ease;
}

.thumbnail-img:hover {
  transform: scale(1.1);
}
.thumbnail-img {
  width: 40px;
  height: 40px;
  border-radius: 4px;
  object-fit: cover;
  cursor: zoom-in;
  transition: transform 0.2s ease;
  margin-right: 4px;
  vertical-align: middle;
}

.thumbnail-img:hover {
  transform: scale(1.1);
}

.thumbnail-download {
  display: inline-block;
  width: 0;
  height: 0;
  overflow: hidden;
}
.thumbnail-img {
  width: 40px;
  height: 40px;
  object-fit: cover;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
  border: 1px solid #ddd;
}

.image-popover {
  padding: 0 !important;
  background-color: transparent !important;
  box-shadow: none !important;
  border: none !important;
}

.preview-img {
  width: 300px; // 放大图片
  height: auto;
  max-height: 400px;
  display: block;
  object-fit: contain;
  border: none;
  border-radius: 0;
  background: transparent;
}

.thumbnail-download {
  display: none; // 你也可以用按钮代替
}
</style>